package protocol

import (
	"encoding/binary"
	"gitee.com/crack007/goose"
	"gitee.com/crack007/goose/core/server"
	"gitee.com/crack007/udp-penetrate/src/common/constant"
	"gitee.com/crack007/udp-penetrate/src/common/dto"
	"gitee.com/crack007/udp-penetrate/src/udpserver/service"
	"net"
)

// 握手请求
type HandshakeReqProtocol struct {
	Uid uint32
}

func NewHandshakeReqProtocol() *HandshakeReqProtocol {
	return &HandshakeReqProtocol{}
}

// server端处理
func (h *HandshakeReqProtocol) Process(session *server.Session, clientConn *net.UDPConn) IProtocol {
	respProtocol := NewHandshakeRespProtocol()
	respProtocol.Host = session.RemoteIp
	respProtocol.Port = session.RemotePort
	userDto := &dto.UserDto{
		Uid:  h.Uid,
		Host: session.RemoteIp,
		Port: session.RemotePort,
	}
	goose.GetLogger().Debug("host=%s port=%d", session.RemoteIp, session.RemotePort)
	service.UserService.CheckIn(userDto, session)
	return respProtocol
}

func (h *HandshakeReqProtocol) Marshall() []byte {
	var body = make([]byte, 4)
	binary.BigEndian.PutUint32(body, h.Uid)
	return body
}

func (h *HandshakeReqProtocol) UnMarshall(data []byte) {
	h.Uid = binary.BigEndian.Uint32(data)
}

func (h *HandshakeReqProtocol) Code() uint32 {
	return constant.CMD_HANDSHANKE_REQ
}
